from django.shortcuts import render


import json

from django.core.exceptions import ObjectDoesNotExist

from api.utils import list_response
from api.models import Gallery
from api.serializers import GallerySerializer

from rest_framework import viewsets
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi
from rest_framework.decorators import action
from django.db.models import Q

from api.mylogger import logger


class BannerViewSet(viewsets.ModelViewSet):
    table_name = Gallery._meta.db_table
    serializer_class = GallerySerializer

    # request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
    #                               required=['name', 'pose_type', 'human_id', 'status'],
    #                               properties={
    #                                   "name": openapi.Schema(type=openapi.TYPE_STRING, description="名称"),
    #                                   "pose_type": openapi.Schema(type=openapi.TYPE_STRING, description="动作所属类别,不填时为 vhuman"),
    #                                   "human_id": openapi.Schema(type=openapi.TYPE_INTEGER, description="对应的虚拟人的id"),
    #                                   "status": openapi.Schema(type=openapi.TYPE_BOOLEAN,description="状态(1激活，0禁用)"),
    #                               }, )
    #
    # @swagger_auto_schema(operation_id='添加横幅', tags=['banner'], request_body=request_body)
    # @action(methods=['POST'], detail=False)
    # def banner_add(self, request):
    #     data = json.loads(request.body.decode('utf8'))
    #     logger.debug("data is ", data)
    #     serializer = GallerySerializer(data=data)
    #     if serializer.is_valid():
    #         res = serializer.save()
    #         res_data = {
    #             "table_name": self.table_name,
    #             "id": res.id,
    #         }
    #         return success_response_with_data(res_data, msg="新增横幅成功")
    #     return JsonResponse(serializer.errors, status=400)
    #
    # request_body_mod = openapi.Schema(type=openapi.TYPE_OBJECT,
    #                                   required=['id', 'name', 'userid', 'username', 'mongoid'],
    #                                   properties={
    #                                       "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="内部Id"),
    #                                       "name": openapi.Schema(type=openapi.TYPE_STRING, description="名称"),
    #                                       "desc": openapi.Schema(type=openapi.TYPE_STRING, description="横幅描述"),
    #                                       "order": openapi.Schema(type=openapi.TYPE_INTEGER, description="顺序号"),
    #                                       "title": openapi.Schema(type=openapi.TYPE_STRING, description="标题"),
    #                                       "url": openapi.Schema(type=openapi.TYPE_STRING, description="url路径"),
    #                                       "status": openapi.Schema(type=openapi.TYPE_BOOLEAN, description="状态(1激活，0禁用)"),
    #                                   }, )
    #
    # @swagger_auto_schema(operation_id='修改横幅', tags=['banner'], request_body=request_body_mod)
    # @action(methods=['POST'], detail=False)
    # def banner_mod(self, request):
    #     data = json.loads(request.body.decode('utf8'))
    #     db_id = data.get('id', None)
    #     logger.debug("db id is ", db_id)
    #     if db_id is None:
    #         return failed_response_with_data(msg="没有id, 修改不了")
    #
    #     serializer = BannerSerializer(data=data)
    #     if serializer.is_valid():
    #         try:
    #             db_ret = serializer.update(instance=Banner.objects.get(id=db_id), validated_data=data)
    #             logger.debug("db_ret", db_ret)
    #             res_data = {
    #                 "table_name": self.table_name,
    #                 "id": db_ret.id
    #             }
    #             return success_response_with_data(res_data, msg="修改横幅成功!")
    #         except ObjectDoesNotExist:
    #             logger.debug("没有修改记录")
    #             return failed_response_with_data(msg=self.table_name+f"没有被修改,未发现id为{db_id}的记录")
    #     return JsonResponse(serializer.errors, status=400)
    #
    # @swagger_auto_schema(operation_id='删除横幅', tags=['banner'], request_body=openapi.Schema(
    #     type=openapi.TYPE_OBJECT,
    #     properties={
    #         "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="横幅表的内部Id"),
    #     },
    # ))
    # @action(methods=['POST'], detail=False)
    # def banner_del(self, request):
    #     data = json.loads(request.body.decode('utf8'))
    #     db_id = data.get('id', None)
    #     logger.debug("banner id is ", db_id)
    #     # qry = Material.objects.filter(id=db_id)
    #     # print(qry.query)
    #     deleted_cnt, _ = Banner.objects.filter(id=db_id).delete()
    #     res_data = {
    #         "table_name": self.table_name,
    #         "id": db_id,
    #         "rows_deleted": deleted_cnt,
    #         "info": "删除" + str(deleted_cnt) + "条记录!",
    #     }
    #     return success_response_with_data(res_data, msg="删除横幅记录成功!")
    #
    # @swagger_auto_schema(operation_id='单个横幅信息', tags=['banner'], request_body=openapi.Schema(
    #     type=openapi.TYPE_OBJECT,
    #     properties={
    #         "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="横幅的内部Id"),
    #     },
    # ))
    # @action(methods=['POST'], detail=False)
    # def banner_one(self, request):
    #     data = json.loads(request.body.decode('utf8'))
    #     db_id = data.get('id', None)
    #     logger.debug("material id is ", db_id)
    #     try:
    #         qry = Banner.objects.get(id=db_id)
    #         logger.debug("material query one", qry)
    #         serializer = BannerSerializer(qry)
    #         return success_response_with_data(serializer.data, msg=self.table_name + "查询单个横幅成功!")
    #     except ObjectDoesNotExist:
    #         logger.debug("没有发现记录")
    #         return failed_response_with_data(None, msg=self.table_name + f"未查到id为{db_id}的横幅!")

    @swagger_auto_schema(operation_id='Gallery列表查询', tags=['gallery'],
                         method='POST',
                         request_body=openapi.Schema(
                             type=openapi.TYPE_OBJECT,
                             properties={
                                 "query": openapi.Schema(type=openapi.TYPE_STRING, description="名称的部分信息"),
                             },
                         )
                         )
    @action(methods=['POST'], detail=False)
    def gallery_list(self, request):
        data = json.loads(request.body.decode('utf8'))
        current_page = data.get("pagenum", 1)
        page_size = data.get("pagesize", 10)
        query = data.get("query", '')

        if current_page < 1:
            current_page = 1
        # 为避免大数据量，用这种方式比较合适，不要用Paginator
        start_row = (current_page - 1) * page_size
        end_row = current_page * page_size

        try:
            objects = Gallery.objects
            if len(query):
                objects = objects.filter(Q(name__icontains=query) | Q(desc__icontains=query) | Q(title__icontains=query) )
            objects = objects.all()
            total = objects.count()
            rows = objects[start_row:end_row]
            logger.debug(f"rows.query {rows.query}")

        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            return list_response()

        serializer = GallerySerializer(rows, many=True)

        return list_response(serializer.data, total, page_size, current_page, self.table_name)
